
//组装参数发送ajax请求去找供应商
$(document).on('click','.action-buynow',function () {

    var categoryType = $(this).attr("categoryType");
    var areaId =  $(".input_addr").val();
    //页面参数效验
    var flag = true;
    $('input.zdy:visible').each(function(){
        if( $(this).val() == '' ){
            $.alert("error","请选择和填写所有选项!",1);
            flag = false;
        }
    });

    // 1)组织 attributesMap ： 找到每个最外层后
    var attributesMap = {};
    var cur = null;	//当前产品
    var  selfPaperParts = [];
    //循环当前部件的ul
    $("ul.level1").children("li:visible").find("ul.level2:visible").each(function () {
        cur = $(this).attr('noneid');
        attributesMap[cur] = {};
            if($(this).find("span.selfPaper").hasClass("atv")){
                selfPaperParts.push(cur);
            }
        $(this).find(".item-con-01[optionid]").each(function () {

            var type = $(this).attr("attributetypevalue");
            var v = "";
            if($(this).find("select").length==1){
                v = $(this).find("select option:selected").val();
            }else if($(this).find("select").length==2){
                v = $(this).find("select").eq(1).val();
            }else{
                v = $(this).find("span.atv").attr("specvalueid");
            }
            attributesMap[cur][type] = v==''?'0':v;
        });
//工艺参数
        $(this).find(".item-con-02[optionid]").each(function () {
            if($(this).find("span.item-con-02-span:visible").hasClass("atv")){
                var type = $(this).attr("attributetypevalue");
                var v = $(this).find("span.atv").attr("specvalueid");
                attributesMap[cur][type] = v==''?'0':v;
            }
        });
    });

    // 2)组织 definitionValueMap ：
    var definitionValueMap = {};
    $("ul.level1").children("li:visible").find("ul.level2:visible").each(function () {
        cur = $(this).attr('noneid');
        definitionValueMap[cur] = {};
        //找到页面上的自定义输入框 存在的记录下来
        $(this).find(".defInput:visible").each(function () {
            var obj = $(this);
            if(obj.find("input:visible").length>0){
                var val = "";
                var type = obj.attr("attributetypevalue");
                $(this).find("input").each(function(){//找到下拉框里面的自定义值
                    val = val+ $(this).val()+",";
                });
                val = val.substr(0,val.length-1).split(",");
                definitionValueMap[cur][type] = val;
            }
        })

    });
    if(JSON.stringify(attributesMap)=='{}'){
        $.alert("error","请选择主部件商品!",1);
        flag = false;
    }

    var params = {
        'categoryId':$("#categoryId").val(),
        'areaId':areaId,
        'categoryType': categoryType,
        'attributesMap': attributesMap,
        'selfPaperParts':selfPaperParts,
        'definitionValueMap': definitionValueMap
    };

    if(flag){
        doAjax("/quote/quotePrice.do","post",{"params":JSON.stringify(params)},function (ret) {
            console.log(ret);
            if(ret.code !== 1){
                $.alert("error",ret.message,1);
                return;
            }
            window.location.href="/quote/quoteProvider.html";
        });
    }

})


//参数部件可选点击
$(document).on('click',".but_up",function(){
    var id = $(this).attr("id");

    if(!$(this).hasClass("atv"))
    {
        $(this).addClass('atv');
        $("ul.level1").find("ul.product-buy-ul[noneid="+id+"]").css("display","block");
    }
    else{

        $(this).removeClass('atv');
        $("ul.level1").find("ul.product-buy-ul[noneid="+id+"]").css("display","none");
    }

})

//组装参数
function installParam() {
    var goodsParamsVO = {};
    var attrRelateOptList = attributeOptionNames();
    var selfDefineParams = defParam();

    $("input[type=hidden].parameter").each(function () {
        var name = $(this).attr('id');
        var value = $(this).val();
        if(name=='spuId'){
            goodsParamsVO['goodsId'] = value;
        }else{
            goodsParamsVO[name] = value;
        }
    });
    goodsParamsVO['quantity'] = $("input.action-quantity-input").val();//组装数量
    goodsParamsVO['areaId'] = $(".input_addr").val();

    var url = "/goods/getSellPrice.json";
    var paramsVO = JSON.stringify(goodsParamsVO);
    var list = JSON.stringify(attrRelateOptList);
    var def = JSON.stringify(selfDefineParams);

    // doAjax(url,'post',{"goodsParamsVO":paramsVO,"attrRelateOptList":list},function (ret) {
    //     var goodsInfo = ret.data;
    //     if(ret.code==1){
    //         $("span.totalPrice").find("strong").text(goodsInfo.basePriceDetail.totalPrice);
    //     }
    // });
}


//变化组装参数
function attributeOptionNames(){
    var partAndAttrRelateOptListMap = {};
    $("ul.level1").find("li.product:visible").each(function () {
        var attributeOptionNames = [];
        $(this).find("p.item-con-01:visible").each(function () {
            var obj = $(this);
            var attrOpt = {};
            var squre = {};
            squre['id'] = obj.attr('optionid');
            squre['attributeType'] = obj.attr('attributetype');
            squre['attributeKey'] = obj.attr('attributekey');
            squre['influenceCraftPriceType'] = obj.attr('influencecraftpricetype');
            squre['joinBuildSku'] = obj.attr('joinbuildsku');
            squre['attributeValueType'] = obj.attr('attributevaluetype');
            attrOpt['squareVO'] = squre;
            if(obj.find("select").length==1){
                //说明有下拉框
                attrOpt['optionId'] = $(this).find("select option:selected").val();
                attributeOptionNames.push(attrOpt);
            }else if(obj.find("select").length==2){
                //说明是材料
                attrOpt['optionId'] = $(this).find("select.optionKey option:selected").val();
                attributeOptionNames.push(attrOpt);
            }else{
                //说明是展开 需要平铺
                obj.find("span.item-con-01-span").each(function () {
                    if($(this).hasClass("atv")){
                    attrOpt['optionId'] = $(this).attr('specvalueid');
                    attributeOptionNames.push(attrOpt);
                    }
                });
            }
        });
        //组装后道工艺的参数
        $(this).find("p.item-con-02:visible").each(function () {
            var obj = $(this);
            obj.find("span.item-con-02-span").each(function () {
                if($(this).hasClass("atv")){
                    var attrOpt = {};
                    var squre = {};
                    squre['id'] = obj.attr('optionid');
                    squre['attributeType'] = obj.attr('attributetype');
                    squre['attributeKey'] = obj.attr('attributekey');
                    squre['influenceCraftPriceType'] = obj.attr('influencecraftpricetype');
                    squre['joinBuildSku'] = obj.attr('joinbuildsku');
                    squre['attributeValueType'] = obj.attr('attributevaluetype');
                    attrOpt['squareVO'] = squre;
                    attrOpt['optionId'] = $(this).attr('specvalueid');
                    attributeOptionNames.push(attrOpt);
                }
            });
        });

        var partId = $(this).attr("clsid");
        partAndAttrRelateOptListMap[partId] = attributeOptionNames;
    });
    return partAndAttrRelateOptListMap;
}

//组装自定义的参数
function defParam(){
    var selfDefineParams = {};
    $("ul.level1").find("li.product:visible").each(function () {
        var map = {};
        $(this).find(".defInput:visible").each(function () {
            var obj = $(this);
            if(obj.find("input").length>=1){
                var str = "";
                obj.find("input").each(function () {
                    str+=$(this).val()+",";
                });
               str = new Array(str.substr(0,str.length-1));
               var id = obj.attr("defId");
               var attributeValueType = obj.attr("attributeValueType");
                map[attributeValueType]=str;
            }
        });
        var partId = $(this).attr("clsid");
        selfDefineParams[partId] = map;
    });
    return selfDefineParams;
}

//输入框 绑定未来事件
$("p").delegate("input.zdy","blur", function(evt){
    evt.stopPropagation(); // 阻止多次判断
    //判断输入是否符合
    var v1 = $(this).val();
    if( isNaN(v1) || parseFloat(v1)<=0 || -1 !== v1.indexOf('-') ){
        $.alert("error","数据填写不合法",0);
        $(this).val('');
        return;
    }

    var max = $(this).attr('max');
    var min = $(this).attr('min');
    if(max=='' || min==''){
        $.alert("error","自定义长度配置错误",0);
        return;
    }
    if( parseFloat(min) > parseFloat(v1) || parseFloat(max) < parseFloat(v1) ){
        $.alert("error","数据填超出合法范围",0);
        $(this).val('');
        return;
    }

    //【P数】 骑马钉、锁线胶装必须是4的倍数
    var divNum = $(this).attr('attributetypevalue');
    var  qmd = "";
    if($("select[attributetypevalue=zhuangding_fangshi]").length>0){
        qmd = $("select[attributetypevalue=zhuangding_fangshi] option:selected").text();
    }else{
        qmd = $("p[attributetypevalue=zhuangding_fangshi]").find("span.atv").text();
    }
    if( Boolean(divNum) && divNum === "p_value" ){
        if(qmd === "骑马钉" || qmd === "锁线胶装"){
            if( v1 % 4 !== 0 ){
                $.alert("error","当【装订方式】选择 [骑马钉] 或者 [锁线胶装] 的时候，【P数】自定义值必须是 4 的倍数！'",0);
                $(this).val('');
                return;
            }
        }
    }
});
//自定义p数检测
$('select[attributetypevalue="zhuangding_fangshi"]').on('change', function(){
    var $selOpt = $(this).find('option:selected');
    var txt = $selOpt.text();
    if( 0 === txt.indexOf("骑马钉") || 0 === txt.indexOf("锁线胶装") ){
        //判断是否自定义
        if($("input[attributetypevalue=p_value]").length>0){
            $("input[attributetypevalue=p_value]").each(function(){
                if($(this).val() % 4 != 0){
                    $.alert("error","当【装订方式】选择 [骑马钉] 或者 [锁线胶装] 的时候，【P数】自定义值必须是 4 的倍数！'",0);
                    $(this).val('');
                }
            })
        }
    }
});


//正常参数d单选 排除下拉框
$(document).on('click',".item-con-01 .item-con-01-span",function(){
    var attrcandef = $(this).parents("p[attributetypevalue]").next("p.defindArea").attr('attrcandef');
    if(attrcandef == 1 && $(this).attr("definitionlength") && $(this).attr("definitionlength").length>2){
        var attributeTypeValue = $(this).parents("p[attributetypevalue]").attr('attributetypevalue');
        var definitionlength = $(this).attr("definitionlength");
        var str = definitionlength.replace(/\[/g,""); str = str.replace(/\]/g,""); var array = str.split(","); var size = array.length/2 >=1? 2 :1;
        array = chunk(array,size);//组装成需要的数组

        //动态拼接html
        var maxmin = array.shift();//删除最前的一个元素，并返回
        var html = "";
        if(array.length==0){
            html += "<input type='text' class='the_custom_ipt last zdy' placeholder="+maxmin[0]+"~"+maxmin[1]+"  max="+maxmin[1]+" min="+maxmin[0]+" attributeTypeValue="+attributeTypeValue+">";
        }else{
            html += "<input type='text' class='the_custom_ipt zdy' placeholder="+maxmin[0]+"~"+maxmin[1]+"  max="+maxmin[1]+" min="+maxmin[0]+" attributeTypeValue="+attributeTypeValue+">";
        }
        if(array.length > 0){
            for(var i=0;i<array.length;i++){
                html+="<img src='https://ziyunoss.oss-cn-hangzhou.aliyuncs.com/pop%2Fmall%2Fimage%2Fzy_img_04.png'> ";
                html+="<input type='text' class='the_custom_ipt last zdy' placeholder="+array[i][0]+"~"+array[i][1]+"  max="+array[i][1]+" min="+array[i][0]+" attributeTypeValue="+attributeTypeValue+">";
            }
        }
        $(this).parents("p[attributetypevalue]").next("p.defindArea").find("span.the_custom").addClass("atv").show();
        //编辑不可点击 必选
        $(this).parents("p[attributetypevalue]").next("p.defindArea").find("span.defInput").show();
        $(this).parents("p[attributetypevalue]").next("p.defindArea").find("span.defInput").html(html);

    }else if(attrcandef == 1){
        $(this).parents("p[attributetypevalue]").next("p.defindArea").find("span.the_custom").hide();
        $(this).parents("p[attributetypevalue]").next("p.defindArea").find("span.defInput").hide();
        $(this).parents("p[attributetypevalue]").next("p.defindArea").find("span.defInput").html('');
    }

    if($(this).find("select").length>=1)
    {
        return;
    }
    if(!$(this).hasClass('atv'))
    {
        $(this).addClass('atv').siblings().removeClass('atv');

        if($(this).parent("p").attr("attributetypevalue") == "zhuangding_fangshi"){
            var txt = $(this).text();
            if( 0 === txt.indexOf("骑马钉") || 0 === txt.indexOf("锁线胶装") ){
                //判断是否自定义
                if($("input[attributetypevalue=p_value]").length>0){
                    $("input[attributetypevalue=p_value]").each(function(){
                        if($(this).val() % 4 != 0){
                            $.alert("error","当【装订方式】选择 [骑马钉] 或者 [锁线胶装] 的时候，【P数】自定义值必须是 4 的倍数！'",0);
                            $(this).val('');
                        }
                    })
                }
            }

        }

    }
    // else{
    //     $(this).removeClass('atv')
    // }
    //installParam();
})


//点击显示工艺
$(document).on('click',".item-con-02 .atv_show",function(){
    var defLength = $(this).attr("customLimitValue");

    if(!$(this).hasClass("atv"))
    {
        $(this).addClass('atv');
        if(defLength){
            var str = defLength.replace(/\[/g,""); str = str.replace(/\]/g,""); var array = str.split(","); var size = array.length/2;
            array = chunk(array,size);//组装成需要的数组
            $(this).siblings("b").find("input").each(function (i,o) {
               if(i==0){
                   $(this).attr("placeholder",array[0][0]+"~"+array[0][1]);
                   $(this).attr("max",array[0][1]);
                   $(this).attr("min",array[0][0]);
               }else{
                   $(this).attr("max",array[1][1]);
                   $(this).attr("min",array[1][0]);
                   $(this).attr("placeholder",array[1][0]+"~"+array[1][1]);
               }
            })
        }
        $(this).next("span").addClass("atv").siblings(".the_custom_input").css("display","inline-block");

        // if($(this).next("span").siblings(".the_custom_input").length==0){
        //
        // }

        $(this).parents("p").find(".item-con-02-span").removeClass('bor-no');
    }
    else{

        $(this).removeClass('atv');
        $(this).parents("p").find(".item-con-02-span").addClass('bor-no').removeClass("atv")
        $(this).parents("p").find(".the_custom_input").css("display","none");

    }

    $(this).next("span").trigger("click");

});

//工艺参数d单选
// $(document).on('click',".item-con-02 .item-con-02-span",function(){
//     if(!$(this).hasClass('bor-no'))
//     {
//         if(!$(this).hasClass('atv'))
//         {
//             $(this).addClass('atv').siblings('span').removeClass('atv');
//             $(this).siblings(".the_custom_input").css("display","inline-block");
//         }
//         else{
//           //  $(this).removeClass('atv')
//             //$(this).siblings(".the_custom_input").css("display","none");
//         }
//     }
//
//
//
// });

//添加工艺显示
$(document).on('click',".tianjia",function(){
    if(!$(this).hasClass("atv")){

        $(this).addClass('atv');
        $(this).parents("ul[noneid]").find(".gongyi").css("display","block")

    }
    else{
        $(this).removeClass('atv');
        $(this).parents("ul[noneid]").find(".gongyi").css("display","none")
    }
})


//自定义数量
$(document).on('click',".the_custom",function(){
    if($(this).hasClass("noClick")){
        return false;
    }

        //得到自定义的长度
        var defLength = $(this).attr("val");
        var id = $(this).attr("defId");
        var parentId = $(this).attr("parentId");
        var attributeTypeValue = $(this).attr("attributetypevalue");
    if(!$(this).hasClass("atv")){
        if(defLength){
            var str = defLength.replace(/\[/g,""); str = str.replace(/\]/g,""); var array = str.split(","); var size = array.length/2 >=1? 2 : 1;
            array = chunk(array,size);//组装成需要的数组
            //动态拼接html
            var maxmin = array.shift();//删除最前的一个元素，并返回
            var html = "";
            if(array.length==0){
             html += "<input type='text' class='the_custom_ipt last zdy' placeholder="+maxmin[0]+"~"+maxmin[1]+"  max="+maxmin[1]+" min="+maxmin[0]+" attributeTypeValue="+attributeTypeValue+">";
            }else{
             html += "<input type='text' class='the_custom_ipt zdy' placeholder="+maxmin[0]+"~"+maxmin[1]+"  max="+maxmin[1]+" min="+maxmin[0]+" attributeTypeValue="+attributeTypeValue+">";
            }
            if(array.length > 0){
                for(var i=0;i<array.length;i++){
                    html+="<img src='https://ziyunoss.oss-cn-hangzhou.aliyuncs.com/pop%2Fmall%2Fimage%2Fzy_img_04.png'> ";
                    html+="<input type='text' class='the_custom_ipt last zdy' placeholder="+array[i][0]+"~"+array[i][1]+"  max="+array[i][1]+" min="+array[i][0]+" attributeTypeValue="+attributeTypeValue+">";
                }
            }
            $("#span_"+id+"_"+parentId).html(html);

        }
        $(this).addClass('atv');
        $(this).parents(".product-list-can").find(".ziding_dow").attr("disabled","disabled")

    }
    else{
        $(this).removeClass('atv');
        $("#span_"+id+"_"+parentId).html('');
        $(this).parents(".product-list-can").find(".ziding_dow").removeAttr("disabled")
    }
})


$(function(){
    //相册
    $.zy_scroll('.thumbnail-list','.flip_prev','.flip_next','.thumbnail-list',4,false);
    $(".thumbnail-list ul li").on('click',function(){
        $(this).addClass('atver').siblings().removeClass('atver');
        $('.product-album-preview').find("img").attr("src",$(this).find("img").attr("src")).css("opacity",0).stop().animate({opacity:1});
    });

    //收藏
    $(document).on('click','.addfav',function(){
        var redirect_url = 'http://www.11ziyun.com/login';
        if(redirect_url=='1'){
            if($('.addfav i').attr("value")=='1'){
//                $.alert('error', '商品已收藏',1);return;
                var goodsId = $('.goodsID').val();
                $(this).find('i').removeClass('atver');
                doAjax('http://www.11ziyun.com/member/del-collect-goods','post',{'goodsId':goodsId},function(data){
                    if(data['result']=='1'){
                        $('.addfav i').attr('value',0)
                        $.alert('success', '取消成功');return;
                    }else{
                        $.alert('error', '取消失败');return;
                    }
                })
            }else{
                var info = {};
                info['goodsIds'] = $('.goodsID').val();
                $(this).find('i').addClass('atver')
                doAjax('http://www.11ziyun.com/member/do-collect-goods','post',info,function(data){
                    if(data['result']=='1'){
                        $('.addfav i').attr('value',1)
                        $.alert('success', '收藏成功');return;
                    }else{
                        $.alert('error', '收藏失败');return;
                    }
                })
            }
        }
        else{
            window.location.href=redirect_url;return;
        }
    })



    //减少数量
    $(document).on('click','.btn-decrease',function(){
        var pic_buy='';
        var input_obj = $(".action-quantity-input");
        var cur_val = Number(input_obj.val());
        if(cur_val  <=1 )return;
        CountAnim(this,cur_val+'',(cur_val-1)+'',-40);
        input_obj.val(Number(cur_val-1));
        if($('.product-big-title span.atver').attr('unit')=='ream')
        {
            pic_buy=Number($('.lPrice').val());
        }
        else if($('.product-big-title span.atver').attr('unit')=='ton')
        {
            pic_buy=Number($('.dPrice').val())
        }
        else if($('.spec-price-box-design.atver').attr('design_cost'))
        {
            pic_buy=Number($('.spec-price-box-design.atver').attr('design_cost'))
            $('.design_cost').text(pic_buy*input_obj.val())
            var urgent = $('.urgent_box .atver').attr('urgent');
            $('.select-design_urgent').text(urgent*input_obj.val());
        }
        else
        {
            pic_buy=Number($('input.price').val())
        }
        if($('.urgent_button').hasClass('atver'))
        {
            $('.urgent').text(input_obj.val()*Number($('.urgent_button').attr('urgent')))

        }

        num_data(pic_buy,input_obj.val())
//            if($('.addcartBuyType').val()=='design_service'){
//                $(".total_num").text(Number($(".select-design_cost").text())+Number($(".select-design_urgent").text()))
//            }else{
//                $(".total_num").text(Number($(".design_cost").text())+Number($(".urgent").text()))
//            }
    });

    //增加数量
    $(document).on('click','.btn-increase',function(){

        var input_obj = $(".action-quantity-input");
        var cur_val = Number(input_obj.val());
        var store = $('.store').val();
        var nostoreSell = $('.nostoreSell').val();
        if(cur_val  >=99999 )return;
//            if(!nostoreSell)
//            {
//                if(input_obj.val()>=store)
//                {
//                    $.alert('error', '库存不足');return;
//                }
//            }
        CountAnim(this,cur_val+'',(cur_val+1)+'',-40);
        input_obj.val(Number(cur_val+1));
        var pic_buy='';
        if($('.product-big-title span.atver').attr('unit')=='ream')
        {
            pic_buy=Number($('.lPrice').val())
        }
        else if($('.product-big-title span.atver').attr('unit')=='ton')
        {
            pic_buy=Number($('.dPrice').val())
        }
        else if($('.spec-price-box-design.atver').attr('design_cost'))
        {
            pic_buy=Number($('.spec-price-box-design.atver').attr('design_cost'))
            $('.design_cost').text(pic_buy*input_obj.val())
            var urgent = $('.urgent_box .atver').attr('urgent');
            $('.select-design_urgent').text(urgent*input_obj.val());
        }
        else
        {
            pic_buy=Number($('input.price').val())
        }
        if($('.urgent_button').hasClass('atver'))
        {
            $('.urgent').text(input_obj.val()*Number($('.urgent_button').attr('urgent')))
        }

        num_data(pic_buy,input_obj.val());
//            if($('.addcartBuyType').val()=='design_service'){
//                $(".total_num").text(Number($(".select-design_cost").text())+Number($(".select-design_urgent").text()))
//            }else{
//                $(".total_num").text(Number($(".design_cost").text())+Number($(".urgent").text()))
//            }
    });

    $(document).on('change','.action-quantity-input',function(){
        var pic_buy='';
        var num = $(this).val();
        if(isNaN(num)){
            $(this).val(1);return;
        }
        if($('.product-big-title span.atver').attr('unit')=='ream')
        {
            pic_buy=Number($('.lPrice').val());
            num = Number(num).toFixed(3);
        }
        else if($('.product-big-title span.atver').attr('unit')=='ton')
        {
            pic_buy=Number($('.dPrice').val());
            num = Number(num).toFixed(6);
        }
        else if($('.spec-price-box-design.atver').attr('design_cost'))
        {
            var urgent = $('.urgent_box .atver').attr('urgent');
            pic_buy=Number($('.spec-price-box-design.atver').attr('design_cost'))
            $('.design_cost').text(pic_buy*$(this).val());
            $('.select-design_urgent').text(urgent*$(this).val());
            num = Number(num).toFixed(0);
        }
        else
        {
//                var store = $('.store').val();
//                var nostoreSell = $('.nostoreSell').val();
//                if(!nostoreSell)
//                {
//                    if(num>=store)
//                    {
//                        $.alert('error', '库存不足');
//                        num = store;
//                        $(this).val(store);
//                    }
//                }
            pic_buy=Number($('input.price').val());
            num = Number(num).toFixed(0);
        }
        if($('.urgent_button').hasClass('atver'))
        {
            $('.urgent').text($(this).val()*Number($('.urgent_button').attr('urgent')))
        }
//            if($('.addcartBuyType').val()=='design_service'){
//                $(".total_num").text(Number($(".select-design_cost").text())+Number($(".select-design_urgent").text()))
//            }else{
//                $(".total_num").text(Number($(".design_cost").text())+Number($(".urgent").text()))
//            }
        num_data(pic_buy,num)
    })
    //数量加减计算
    function num_data(pic,num,dis)
    {
        var info = {};
        if(num>=99999){
            num = 99999;
        }

        installParam();//组装参数

    }

    var CountAnim=function(obj,j,l,num){
        var txtCount = $('.action-quantity-input');
        var p=$(obj).parents('.input_box');
        var k='';
        var j=j.split('');
        txtCount.css('color','#fff');
        for (var s = 0; s < j.length; s++)
        {
            k += '<i style="position:relative;">' + j[s] + "</i>";
        }
        p.prepend('<i class="upspan" >' + k + "</i>");

        var m='';
        var l=l.split('');
        for (var n = 0; n <l.length; n++)
        {
            m += '<i style="position:relative;">' + l[n] + '</i>';

        }
        p.append('<i class="downspan" style="top:'+(-num)+'px;">' + m + "</i>");
        var d = $(".downspan i:last");
        var u= $(".upspan i:last");

        u.animate({top: num}, "10");
        d.animate({top: num}, "10",function(){
            $('.downspan,.upspan').remove();
            txtCount.css('color','#333');
        });
    }
});

//地址
$(".address_text").hover(function(){
    $(".address_select").show();
    if($(".address_tab span").index('.atver')!=-1)
    {
        $(".address_con").eq(0).show();
    }


},function(){

    $(".address_select").hide();
    $(".address_con").hide().eq(1).show();
    $(".address_tab i").eq(2).text('请选择').hide();
    $(".address_tab span").removeClass('atver').eq(1).addClass('atver');
})
$(".address_tab span").each(function(i, o) {
    $(o).click(function(){
        $(o).addClass('atver').siblings().removeClass('atver');
        $(".address_con").hide().eq(i).show();
    })
});
$.select_add('address_op',region_Data,1323);//默认湖北武汉江汉区
$(".address_con").each(function(i, o) {
    $(o).html($(".address_op").eq(i).html());
    $(o).find("option").each(function(index, element) {
        $(element).wrapAll(document.createElement("span"));
    });
    $(o).on('click','option',function(){
        $(".address_op").eq(i).val($(this).attr('value'))
        $(".address_tab span").eq(i).find('i').text($(this).text());
        var id=$(this).attr('value')
        add_div(region_Data,id,i);
    })
});

function add_div(jsonData,id,index)
{
    getJsonLength=function(jsonData)
    {
        var jsonLength = 1;
        for(var item in jsonData){
            jsonLength++;
        }
        return jsonLength;

    };

    var len=getJsonLength(region_Data);

    if(index==0)
    {
        $(".address_con").eq(1).html('');
        $(".address_con").eq(2).html('');
        $(".address_tab i").eq(1).text('请选择');
        $(".address_tab i").eq(2).text('请选择').hide();
        //for(var i=1;i<len;i++)
        for ( i in jsonData)
        {
            if(jsonData[i]!=undefined && jsonData[i]['p_region_id']==id)
            {
                $(".address_con").eq(1).append("<option value="+jsonData[i]["region_id"]+">"+jsonData[i]["local_name"]+"</option>");

            }
        }
        $(".address_con").eq(1).find("option").each(function(index, element) {
            $(element).wrapAll(document.createElement("span"));
        });
        $(".address_tab span").removeClass("atver").eq(1).addClass("atver");
        $(".address_con").hide().eq(1).show();

    }
    if(index==1)
    {
        $(".address_con").eq(2).html('');
        $(".address_tab i").eq(2).text('请选择').show();
        //for(var i=1;i<len;i++)
        for ( i in jsonData)
        {
            if(jsonData[i]!=undefined && jsonData[i]['p_region_id']==id)
            {
                $(".address_con").eq(2).append("<option value="+jsonData[i]["region_id"]+">"+jsonData[i]["local_name"]+"</option>")

            }
        }
        $(".address_con").eq(2).find("option").each(function(index, element) {
            $(element).wrapAll(document.createElement("span"));
        });
        if($(".address_con").eq(2).text()=='')
        {
            $(".address_tab span").eq(2).hide().html('<i></i>');
            $(".address_text a").text($(".address_tab").text());
            $(".address_select").hide();
            $(".input_addr").val(id);

            installParam();

        }
        else
        {
            $(".address_tab span").eq(2).show().html('<i>请选择</i>');

        }
        $(".address_tab span").removeClass("atver").eq(2).addClass("atver");
        $(".address_con").hide().eq(2).show();
    }
    if(index==2)
    {
        $(".address_text a").text($(".address_tab").text());
        $(".address_select").hide();
        $(".input_addr").val(id);

        installParam();

        // doAjax('http://www.11ziyun.com/goods/getFreightprice','post',{'areaId':id,'productId':$('.productID').val(),'count':$('.action-quantity-input').val()},function(params){
        //     $('.areaId').val(id);
        //     $('.freightPrice').text('￥'+params['data']);
        // })
    }
}

//切割数组，分组
function chunk(arr,size){
    var arr1 = [];
    if(size>1){
        for(var i=0;i<arr.length;i=i+size){
            var arr2 =arr;
            arr1.push(arr2.slice(i,i+size));
        }
        return arr1;
    }else{
        arr1.push(arr.slice(0,2));
        return arr1;
    }
}